import 'package:flutter/material.dart';
import '../components/my_editable_text.dart' as MyEdit;

class KeyController {
  final MyEdit.TextEditingController myTextController;
  final FocusNode focusNode;
  KeyController({@required this.myTextController, @required this.focusNode});

  String get text => myTextController.text;

  set value(TextEditingValue newValue) {
    newValue = newValue.copyWith(
        // 修正由于默认值导致的Bug
        composing: TextRange(
            start: newValue.composing.start < 0 ? 0 : newValue.composing.start,
            end: newValue.composing.end < 0 ? 0 : newValue.composing.end),
        selection: newValue.selection.copyWith(
            baseOffset: newValue.selection.baseOffset < 0
                ? 0
                : newValue.selection.baseOffset,
            extentOffset: newValue.selection.extentOffset < 0
                ? 0
                : newValue.selection.extentOffset));
    myTextController.value = newValue;
  }

  ///删除一个字符,一般用于键盘的删除键
  TextSelection get selection => myTextController.selection;
  deleteOne() {
    if (!focusNode.hasFocus) {
      return;
    }
    if (selection.baseOffset <= 0) return;
    String newText = '';
    // print('selection.extentOffset${selection.extentOffset}');
    // print('selection.baseOffset${selection.baseOffset}');
    if (selection.baseOffset != selection.extentOffset) {
      newText = selection.textBefore(text) + selection.textAfter(text);
      // print('结尾$newText');
      value = TextEditingValue(
          text: newText,
          selection: selection.copyWith(
              baseOffset: selection.baseOffset,
              extentOffset: selection.baseOffset));
    } else {
      //表示光标在中间
      newText = text.substring(0, selection.baseOffset - 1) +
          selection.textAfter(text);
      // print('中间$newText');
      value = TextEditingValue(
          text: newText,
          selection: selection.copyWith(
              baseOffset: selection.baseOffset - 1,
              extentOffset: selection.baseOffset - 1));
    }
  }

  /// 在光标位置添加文字,一般用于键盘输入
  addText(String insertText) {
    if (!focusNode.hasFocus) {
      return;
    }
    String newText =
        selection.textBefore(text) + insertText + selection.textAfter(text);
    value = TextEditingValue(
        text: newText,
        selection: selection.copyWith(
            baseOffset: selection.baseOffset + insertText.length,
            extentOffset: selection.baseOffset + insertText.length));
  }

  //移除焦点
  removeFoucs() {
    focusNode.unfocus();
  }

  deleteAll() {
    value = TextEditingValue(
        text: '',
        selection: selection.copyWith(baseOffset: 0, extentOffset: 0));
  }
}
